package com.zyl.callery_kt

import android.os.Bundle
import android.os.Handler
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import kotlinx.android.synthetic.main.fragment_gallery.*


class GalleryFragment : Fragment() {

    private lateinit var galleryViewModel: GalleryViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.swipeIndicator->{
                swipeLayoutGallery.isRefreshing = true // 改变界面为刷新状态
                Handler().postDelayed(Runnable { galleryViewModel.fetchData() },1000)//刷新，延迟1秒钟
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu,menu)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)//显示Menu

        val galleryAdapter = GalleryCell()
        recyclerView.apply {
            adapter = galleryAdapter  //设置适配器
            layoutManager = GridLayoutManager(requireContext(),2)  //设置位网状，2列
        }

        //获得ViewModel
        galleryViewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(GalleryViewModel::class.java)

        galleryViewModel.photoListLive.observe(this, Observer {
            galleryAdapter.submitList(it)
            swipeLayoutGallery.isRefreshing = false
        } )

        galleryViewModel.photoListLive.value?:galleryViewModel.fetchData()

        //下拉刷新
        swipeLayoutGallery.setOnRefreshListener {
            galleryViewModel.fetchData()
        }

    }


}